package windows;

import iterfaces.Ships;

import java.net.*;
import Chat.*;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;

import java.awt.*;
import java.awt.event.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.awt.Graphics;
import java.awt.Dimension;
import javax.swing.JPanel;
import drawEngine.DrawPanel;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Rectangle;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JList;
import java.awt.event.WindowStateListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

import controllers.Config;
import controllers.DataInsertion;
import controllers.Map;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JSeparator;
import javax.swing.JLabel;

import ships.Ship;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import controllers.ObjectsOnMap;
import javax.swing.border.BevelBorder;



/**
 *
 * @author Gertjan
 */
public class GameConsole extends javax.swing.JFrame {
	
	private A_Chat_Client ChatClient;
	public static String UserName;
	public static boolean ConnectAllowed = false;
	private int WindowState = 0;
	
	public static int PORT;
	public static String HOST;
	
	public static JTextArea TA_CONVERSATION = new javax.swing.JTextArea();
	private static JScrollPane SP_CONVERSATION = new JScrollPane();
	public static JList JL_ONLINE = new JList();


    private WindowManager windowManager;
	/**
     * Creates new form GameConsole
     */
    public GameConsole(WindowManager windowManager) {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowActivated(WindowEvent e) {
				WindowState++;
				if(WindowState == 1)
				{
					Connect();
					
      				//Elke seconden snapshot maken
      				Timer snapShotTimer = new Timer();
      				snapShotTimer.schedule( new TimerTask() {
      					public void run() {
            				if(Map.getMap().dObjects != null) {
            					Ships o = Map.getMap().dObjects.get(0);
            					String ownObject = Map.getMap().dObjects.get(0).getShipName();
            					
            					DataInsertion.autoLogInsert(ownObject, "HP: "+o.getHealthPoints());
            					DataInsertion.autoLogInsert(ownObject, "Infrared: "+Config.getConfig().infrared + " Radar: "+Config.getConfig().radar + " Sonar: "+Config.getConfig().sonar);
            					DataInsertion.autoLogInsert(ownObject, "currPos: "+o.getPosition());
            					DataInsertion.autoLogInsert(ownObject, "currWP: "+o.getCurrentWayPoint());
            					DataInsertion.autoLogInsert(ownObject, "lastWP: "+o.getLastWaypoint());
            					DataInsertion.autoLogInsert(ownObject, "Hit :" + "Cords: ");
            					
            					String transportObject = Map.getMap().dObjects.get(1).getShipName();
            					Ships p = Map.getMap().dObjects.get(1);
            					
            					DataInsertion.autoLogInsert(transportObject, "HP: "+p.getHealthPoints());
            					DataInsertion.autoLogInsert(transportObject, "currPos: "+p.getPosition());
            					DataInsertion.autoLogInsert(transportObject, "currWP: "+o.getCurrentWayPoint());
            					DataInsertion.autoLogInsert(transportObject, "lastWP: "+o.getLastWaypoint());
            					
            					double maxHealth = o.getFullHealthPoints();
            					double currentHealth = o.getHealthPoints();
            					double percentageLeft = currentHealth / maxHealth * 100;
            					Config.getConfig().PercentageLeft = percentageLeft;
            					/*if (percentageLeft <= 90 && percentageLeft > 80) {
            						if (Config.getConfig().selectedWeapon == "Torpedo") {
            							Config.getConfig().selectedWeapon = "Cannon";
            						}
            					}*/            					
            					if (percentageLeft <= 80 && percentageLeft > 70) {
            						o.setMaximumSpeed((int) (o.getMaximumSpeed() / 2));
            					}            					
            					/*if (percentageLeft <= 70 && percentageLeft > 60) {
            						if (Config.getConfig().selectedWeapon == "Cannon") {
            							Config.getConfig().selectedWeapon = "Goalkeeper";
            						}
            					}            					
            					if (percentageLeft <= 60 && percentageLeft > 50) {
            						
            					}            					
            					if (percentageLeft <= 50 && percentageLeft > 40) {
            						if (Config.getConfig().selectedWeapon == "Goalkeeper") {
            							Config.getConfig().selectedWeapon = "Missile";
            						}
            					}            					
            					if (percentageLeft <= 40 && percentageLeft > 30) {
            						if (Config.getConfig().selectedWeapon == "Missile") {
            						Config.getConfig().selectedWeapon = "None";
            						}
            					}   */         					
            					if (percentageLeft <= 30 && percentageLeft > 20) {
            						o.setMaximumSpeed((int) (o.getMaximumSpeed() / 4));
            					}            					
            					if (percentageLeft <= 20 && percentageLeft > 10) {
            						Config.getConfig().infrared = false;
            						Config.getConfig().radar = false;
            						Config.getConfig().sonar = false;
            					}
            					if (percentageLeft <=10 && percentageLeft > 0) {
            						for (int wp = 0; wp < 20; wp++) {	
            							try {
            							o.removeLastWaypoint();
            							}
            							catch(Exception e) {
            								e.printStackTrace();
            							}
            							finally {
            								//
            							}
            						}
            					}
            					if (percentageLeft < 10) {
            						o.deleteObject(true);
            					}
            				}
      					}
      				}, 0, 1*1000);
				}
				
			}
		});
		getContentPane().setMinimumSize(new Dimension(1366, 700));
		setSize(new Dimension(1366, 755));
		setExtendedState(MAXIMIZED_BOTH);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	this.windowManager = windowManager;
		setTitle("CMS - Console");
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		JMenu mnFile = new JMenu("File");
		menuBar.add(mnFile);
		
		JMenuItem mntmDisconnect = new JMenuItem("Disconnect");
		mntmDisconnect.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {			
			}
			@Override
			public void mouseReleased(MouseEvent arg0) {				
				try
				{					
					ChatClient.DISCONNECT();
				}
				catch(Exception y) {y.printStackTrace(); }
			}
		});
		mnFile.add(mntmDisconnect);
        initComponents();
    }

    public void Connect()
    {
    	try
    	{

    		Socket SOCK = new Socket(HOST,PORT);
    		System.out.println("You connected to: "+ HOST);
    		
    		ChatClient = new A_Chat_Client(SOCK);
    		System.out.println("ChatClient: " + ChatClient);
    		Config.getConfig().chatClient = ChatClient;
    		
    		//Send name to online list
    		PrintWriter OUT = new PrintWriter(SOCK.getOutputStream());
    		OUT.println(UserName);
    		OUT.flush();
    		
    		Thread X = new Thread(ChatClient);
    		X.start();		
    	}
    	catch(Exception X)
    	{
    		System.out.print(X);
    		JOptionPane.showMessageDialog(null, "Server not Responding." + HOST + PORT);
    		System.exit(0);
    	}
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
    	jSlider_Speed = new javax.swing.JSlider();
        jSlider_Speed.setBounds(1105, 24, 35, 109);        
    	jSlider_Speed.addChangeListener(new ChangeListener() {
    		public void stateChanged(ChangeEvent e) {
    			int speedPercentage = jSlider_Speed.getValue();
    			Config.getConfig().setSpeed(speedPercentage);
    		}
    	});
        jSlider_Speed.setBounds(1105, 24, 35, 109);
        
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator1.setBounds(1005, 133, 335, 13);
        jSeparator2 = new javax.swing.JSeparator();
        jSeparator2.setBounds(813, 11, 2, 0);
        jSeparator3 = new javax.swing.JSeparator();
        jSeparator3.setBounds(813, 133, 19, 0);
        jSeparator4 = new javax.swing.JSeparator();
        jSeparator4.setBounds(1005, 188, 335, 13);
        jSeparator5 = new javax.swing.JSeparator();
        jSeparator5.setBounds(1005, 11, 335, 2);
        jSeparator7 = new javax.swing.JSeparator();
        jSeparator7.setBounds(1004, 234, 335, 8);
        jSeparator8 = new javax.swing.JSeparator();
        jSeparator8.setBounds(813, 260, 2, 0);
        jComboBox2 = new javax.swing.JComboBox();
        jComboBox2.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		Config.getConfig().selectedWeapon = (String) jComboBox2.getSelectedItem();
        	}
        });
        jComboBox2.addMouseMotionListener(new MouseMotionAdapter() {
        	public void mouseMoved(MouseEvent e) {
        		int temp = jComboBox2.getSelectedIndex();
        		jComboBox2.removeAllItems();
        		String[] weapons = Config.getConfig().weaponsOnShip;
        	    for(String s:weapons){
        	        jComboBox2.addItem(s);
        	    }
        	    jComboBox2.setSelectedIndex(temp);
        	}
        });
        jComboBox2.setBounds(1004, 267, 200, 20);
        jButton1 = new javax.swing.JButton();
        jButton1.setBounds(1215, 266, 124, 23);
        jLabel1 = new javax.swing.JLabel();
        jLabel1.setBounds(1163, 67, 152, 14);
        jLabel2 = new javax.swing.JLabel();
        jLabel2.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel2.setBounds(1005, 140, 335, 14);
        jLabel3 = new javax.swing.JLabel();
        jLabel3.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel3.setBounds(1005, 201, 335, 14);
        
        jProgressBar_ShipHealth = new javax.swing.JProgressBar();
        jProgressBar_ShipHealth.setBounds(1005, 217, 334, 14);
        
        jProgressBar_ShipHealth.setMinimum(0);
        jProgressBar_ShipHealth.setMaximum(100);
        jProgressBar_ShipHealth.setValue(100);
        jProgressBar_ShipHealth.setStringPainted(true);
        //Border border = BorderFactory.createTitledBorder("Reading...");
        //jProgressBar_ShipHealth.setBorder(border);
        
        jSlider_Speed.setOrientation(javax.swing.JSlider.VERTICAL);

        jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);

        jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL);

        jSeparator8.setOrientation(javax.swing.SwingConstants.VERTICAL);

        String[] weapons = Config.getConfig().weaponsOnShip;
        jComboBox2.setModel(new DefaultComboBoxModel(weapons));

        jButton1.setText("Launch");
        jButton1.setActionCommand("Launch");

        jLabel1.setText("Mobility Controls");

        jLabel2.setText("Sensors");

        jLabel3.setText("Vessel Status");
        getContentPane().setLayout(null);
        getContentPane().add(jSeparator8);
        getContentPane().add(jSeparator7);
        getContentPane().add(jProgressBar_ShipHealth);
        getContentPane().add(jLabel3);
        getContentPane().add(jSeparator2);
        getContentPane().add(jSeparator3);
        getContentPane().add(jSeparator5);
        getContentPane().add(jSlider_Speed);
        getContentPane().add(jLabel1);
        getContentPane().add(jSeparator1);
        getContentPane().add(jSeparator4);
        getContentPane().add(jLabel2);
        getContentPane().add(jComboBox2);
        getContentPane().add(jButton1);        
        TA_CONVERSATION.setBounds(76, 369, 360, 79);
		SP_CONVERSATION.setLocation(1005, 352);
		SP_CONVERSATION.setSize(340, 183);
		SP_CONVERSATION.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		SP_CONVERSATION.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		SP_CONVERSATION.setViewportView(TA_CONVERSATION);
		getContentPane().add(SP_CONVERSATION);
        
                TA_CONVERSATION.setColumns(20);
                TA_CONVERSATION.setRows(5);
                
                TF_Message = new JTextField();
                TF_Message.setBounds(1005, 540, 340, 20);
                getContentPane().add(TF_Message);
                TF_Message.setColumns(10);
                
                JPanel panel = new DrawPanel();
                panel.setBounds(10, 11, 985, 664);
                getContentPane().add(panel);
                
                JButton btnSend = new JButton("Send");
                TF_Message.setAction(send);
                btnSend.setAction(send);
                btnSend.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "SEND");
                btnSend.getActionMap().put("SEND", send);
               
                btnSend.addActionListener(new ActionListener() {
                	public void actionPerformed(ActionEvent arg0) {
                		
                		if(!TF_Message.getText().equals(""))
                		{                			
                			ChatClient.SEND(TF_Message.getText());
                			TF_Message.requestFocus();
                		}
                	}
                });
                btnSend.setBounds(1005, 571, 236, 31);
                getContentPane().add(btnSend);
                
                JButton btnRemoveLastWaypoint = new JButton("Remove last waypoint");
                btnRemoveLastWaypoint.addMouseListener(new MouseAdapter() {
                	@Override
                	public void mouseClicked(MouseEvent e) {
                		Map.getMap().dObjects.get(0).removeLastWaypoint();               	
                	}
                });
                btnRemoveLastWaypoint.setBounds(1004, 306, 335, 23);
                getContentPane().add(btnRemoveLastWaypoint);
                
                JSeparator separator = new JSeparator();
                separator.setBounds(1004, 298, 335, 12);
                getContentPane().add(separator);
                
                lblWeaponsystem = new JLabel("Weaponsystem");
                lblWeaponsystem.setHorizontalAlignment(SwingConstants.CENTER);
                lblWeaponsystem.setBounds(1004, 246, 335, 14);
                getContentPane().add(lblWeaponsystem);
                
                JSeparator separator_1 = new JSeparator();
                separator_1.setBounds(1004, 340, 335, 12);
                getContentPane().add(separator_1);
                
                JScrollPane scrollPane = new JScrollPane();
                scrollPane.setBounds(1249, 571, 91, 109);
                getContentPane().add(scrollPane);
                scrollPane.setViewportView(JL_ONLINE);
                JL_ONLINE.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
                JL_ONLINE.setBackground(SystemColor.controlHighlight);
               
                


        	
    }// </editor-fold>//GEN-END:initComponents

    private Action send = new AbstractAction("send")
    {
    	public void actionPerformed(ActionEvent e)
    	{
    		if(!TF_Message.getText().equals(""))
    		{                			
    			ChatClient.SEND(TF_Message.getText());
    			TF_Message.requestFocus();
    		}
    	}
    };
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JProgressBar jProgressBar_ShipHealth;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JSeparator jSeparator7;
    private javax.swing.JSeparator jSeparator8;
    private javax.swing.JSlider jSlider_Speed;
   // private javax.swing.JTextArea TA_CONVERSATION;
    public static JTextField TF_Message;
    private JLabel lblWeaponsystem;
}
